package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentMongoRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService{

    @Autowired
    private StrategyCommentMongoRepository repository;//简单crud
    @Autowired
    private MongoTemplate template;//高级查询


    public void save(StrategyComment comment) {
        comment.setCreateTime(new Date());
        repository.save(comment);
    }

    public Page query(StrategyCommentQuery qo) {
        //PageResult
        Query query = new Query();

        //设置条件
        if (qo.getDetailId() != -1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }

        //设置分页对象
        PageRequest pageble = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        //查询总数
        long count = template.count(query, StrategyComment.class);

        //分页
        query.with(pageble);

        //查当前页显示的集合
        List<StrategyComment> list = template.find(query, StrategyComment.class);

        //封装为分页对象
        return new PageImpl(list,pageble,count);
    }


    public void commentThumbUp(String commentId, Long userId) {
        //判断当前用户是否在点赞集合中
        Optional<StrategyComment> op = repository.findById(commentId);
        StrategyComment strategyComment = op.get();//获取当前攻略评论
        if (strategyComment==null){
            throw new LogicException("参数异常");
        }
        List<Long> list = strategyComment.getThumbuplist();//获取当前点赞列表
        //判断当前登录用户是否在点赞集合中
        if (list.contains(userId)){
            //在,表示是取消点赞,点赞数减1,并从点赞列表中移除当前用户
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() - 1);
            list.remove(userId);
        }else {
            //不在,表示是点赞操作,点赞数加1,并添加当前用户到点赞列表中
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() + 1);
            list.add(userId);
        }
        //处理完之后需要更新攻略评论
        repository.save(strategyComment);
    }
}
